var SelectList = []//(用于记录被选中的行)
$(function () {
    $("#jqGrid").jqGrid({
        url: 'sys/database/list',
        datatype: "json",
        colModel: [			
			{ label: 'ID', name: 'id', width: 30, key: true , hidden: true},
			{ label: '数据库名称', name: 'name', width: 200},
			{ label: '数据库连接', name: 'url' , width: 250},
            { label: '用户名', name: 'userName', width: 50 },
            { label: '密码', name: 'password', width: 50 },
            { label: '数据源名', name: 'dbName', width: 80 },
            { label: 'SCHEMA', name: 'dbSchema', width: 80 },
            { label: '驱动程序', name: 'driver', width: 120 },
            { label: '主机地址', name: 'hostName', width: 80 },
            { label: '端口', name: 'port', width: 80 },
            { label: '数据库类型', name: 'dbType', width: 100 },
            { label: '创建时间', name: 'createDt', width: 100 }
        ],
		viewrecords: true,
        height: 405,
        rowNum: 10,
		rowList : [10,30,50,100,200],
        rownumbers: true,
        rownumWidth: 40,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        onSelectAll: function (aRowids, status) {
            if (status) {
                for (var i = 0; i < aRowids.length; i++) {
                    if (SelectList.indexOf(aRowids[i]) == -1) {//每一次勾选时，检查该行是否在SelectList中，
                        //若在，则在SelectList中删除该记录
                        //（翻页也会触发onselect事件，所以需检查该行是否在unselects中）
                        SelectList.push(aRowids[i]);
                    }
                }
            } else {
                for (var i = 0; i < aRowids.length; i++) {
                    if (SelectList.indexOf(aRowids[i]) > -1) {//每一次勾选时，检查该行是否在SelectList中，
                        //若在，则在SelectList中删除该记录
                        //（翻页也会触发onselect事件，所以需检查该行是否在unselects中）
                        SelectList.splice($.inArray(aRowids[i], SelectList), 1)
                    }
                }
            }
        },
        onSelectRow: function (rowid, status) {
            if (status) { // 每一次取消选中时，将该行id添加到SelectList中
                if (SelectList.indexOf(rowid) == -1) {//每一次勾选时，检查该行是否在SelectList中，
                    //若在，则在SelectList中删除该记录
                    //（翻页也会触发onselect事件，所以需检查该行是否在unselects中）
                    SelectList.push(rowid);
                }
            } else {
                if (SelectList.indexOf(rowid) > -1) {//每一次勾选时，检查该行是否在SelectList中，
                    //若在，则在SelectList中删除该记录
                    //（翻页也会触发onselect事件，所以需检查该行是否在unselects中）
                    SelectList.splice($.inArray(rowid, SelectList), 1)
                }
            }
        },
        gridComplete:function(){
            var ids = $("#jqGrid").jqGrid('getDataIDs');
            for (var i = 0; i < ids.length; i++) {
                if ((SelectList.indexOf(ids[i]) > -1)) {
                    $("#jqGrid").jqGrid('setSelection', ids[i]);
                }
            }
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});
var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			name: null
		}
	},
	methods: {
		query: function () {
			$("#jqGrid").jqGrid('setGridParam',{ 
                postData:{'name': vm.q.name},
                page:1 
            }).trigger("reloadGrid");
		},
		add: function() {
            $('#databaseEditForm').formReset();
            $("#operateMode").val('add');
            $('#databaseEditModal').modal({backdrop: false});
            $("#submitDatabase").show();
		},
        update: function() {
            var ids=$("#jqGrid").jqGrid("getGridParam","selarrrow");
            if(ids.length == 1){
                var rowid = $("#jqGrid").jqGrid("getGridParam","selrow");
                var rowData = $("#jqGrid").jqGrid('getRowData',rowid);
                $('#databaseEditForm').formReset();
                $("#databaseEditForm").formLoadData(rowData);
                $("#submitDiv").show();
                $("#operateMode").val('update');
                $("#id").val(rowData.id);
                $('#databaseEditModal').modal({backdrop: false});
                $("#submitDatabase").show();
            }else{
                alert("请选择一行数据");
                return;
            }

        },
        del: function() {
            if(SelectList.length  == 0){
                alert("请选择一条记录");
                return ;
            }
            confirm("确认删除数据库" + SelectList.join() + "信息？", function(result){
                if(result) {
                    $.post("/sys/database/delete/"+SelectList.join() , function (result) {
                        if (typeof(result) == "string") {
                            result = $.parseJSON(result);
                        }
                        if (result.code == '0') {
                            //刷新
                            $("#jqGrid").jqGrid('setGridParam',{page:1}).trigger("reloadGrid");
                        }
                        alert(result.msg);
                    });
                }
            });
        }
	}
});

$('#submitBtn').on('click', function () {
    var name = $("#name").val();
    if(name.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("数据库名称不能为空");
        return;
    }
    var url = $("#url").val();
    if(url.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("数据库连接不能为空");
        return;
    }
    var hostName = $("#hostName").val();
    if(hostName.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("主机地址不能为空");
        return;
    }
    var port = $("#port").val();
    if(port.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("主机端口不能为空");
        return;
    }
    var userName = $("#userName").val();
    if(userName.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("用户名不能为空");
        return;
    }
    var password = $("#password").val();
    if(password.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("密码不能为空");
        return;
    }
    var dbName = $("#dbName").val();
    if(dbName.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("数据源名不能为空");
        return;
    }
    var dbSchema = $("#dbSchema").val();
    if(dbSchema.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("SCHEMA不能为空");
        return;
    }
    var dbType = $("#dbType").val();
    if(dbType.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("数据库类型不能为空");
        return;
    }
    var driver = $("#driver").val();
    if(driver.replace(/(^\s*)|(\s*$)/g, "").length ==0){
        alert("驱动程序不能为空");
        return;
    }
    $("#submitBtn").button("loading");
    var formObject = {};
    var formArray =$("#databaseEditForm").serializeArray();
    $.each(formArray,function(i,item){
        formObject[item.name] = item.value;
    });
    var operateMode = $("#operateMode").val();
    var url = "";
    if (operateMode == "add") {
        url =  "/sys/database/insert";
    } else if (operateMode == "update") {
        url = "/sys/database/update";
    }
    $.post(url, JSON.stringify(formObject), function (result) {
        $("#submitBtn").button("reset");
        if (typeof(result) == "string") {
            result = $.parseJSON(result);
        }
        $("#submitBtn").button("reset");
        if (result.code == '0') {
            $('#databaseEditModal').modal('hide');
            //刷新
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'name': vm.q.name},
                page:1
            }).trigger("reloadGrid");
        }
        alert(result.msg);
    });
});